package com.kitten.dataAlign.job.dataAlign;

import cn.hutool.core.collection.CollUtil;
import com.kitten.dataAlign.constants.RedisKeyConstants;
import com.kitten.dataAlign.constants.TableConstants;
import com.kitten.dataAlign.domain.mapper.DeleteMapper;
import com.kitten.dataAlign.domain.mapper.SelectMapper;
import com.kitten.dataAlign.domain.mapper.UpdateMapper;
import com.kitten.dataAlign.rpc.SearchRpcService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author kitten
 * @desc: 用户被收藏数对齐
 */
@Slf4j
@Component
public class UserCollectCountShardingXxlJob {

    @Resource
    private SelectMapper selectMapper;
    @Resource
    private UpdateMapper updateMapper;
    @Resource
    private DeleteMapper deleteMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private SearchRpcService searchRpcService;

    @Value("${table.shards}")
    private int tableShards;

    @XxlJob(value = "userCollectCountShardingJobHandler")
    public void userLikeCountShardingJobHandler() throws Exception {
        // 分片序号
        int shardIndex = XxlJobHelper.getShardIndex();
        // 分片总数
        int shardTotal = XxlJobHelper.getShardTotal();

        XxlJobHelper.log("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
        log.info("分片参数：当前分片序号 = {}, 总分片数 = {}", shardIndex, shardTotal);
        // 表后缀
        String date = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("yyyyMMdd")); // 转字符串
        String tableNameSuffix = TableConstants.buildTableNameSuffix(date, shardIndex);
        int batchSize = 1000; // 每批查询 1000 条
        int processedCount = 0; // 已处理的记录数


        // 循环这一批发生变更的用户 ID
        for( ; ; ) {
            List<Long> userIds = selectMapper.selectBatchFromDataAlignUserCollectCountTempTable(tableNameSuffix, batchSize);
            if (CollUtil.isEmpty(userIds)) {
                break;
            }
            userIds.forEach(userId -> {
                int collectCount = selectMapper.selectCountFromUserCollectTableByUserId(userId);

                // 更新 t_user_collect 表
                int updateCount = updateMapper.updateUserCollectCountByUserId(userId, collectCount);

                if (updateCount > 0) {
                    String key = RedisKeyConstants.buildCountUserKey(userId);   // count:user:userId
                    Boolean hasKey = redisTemplate.hasKey(key);
                    if (hasKey) {
                        redisTemplate.opsForHash().put(key, RedisKeyConstants.FIELD_USER_COLLECT_TOTAL, collectCount);
                    }
                }
            });
            // 批量物理删除这一批次记录
            deleteMapper.deleteBatchFromDataAlignUserCollectCountTempTable(tableNameSuffix, userIds);
            processedCount += userIds.size();
        }

        XxlJobHelper.log("本次处理记录数：{}", processedCount);
    }

}
